//
//  MyCoinViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/30.
//

#import "MyCoinViewController.h"
#import "MyCoinTopView.h"
#import "MyCoinListCell.h"
#import "TaskListManager.h"
#import "TaskListModel.h"
#import "GetUserInfoManager.h"
#import "JPTabBarController.h"


@interface MyCoinViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)MyCoinTopView *topView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)TaskListManager *taskListManager;
@property(nonatomic,strong)NSMutableArray *taskArr;
@property(nonatomic,strong)GetUserInfoManager *userInfoManager;
@property(nonatomic,strong)UIImageView *topBgImageView;

@end

@implementation MyCoinViewController

-(TaskListManager *)taskListManager{
    if(!_taskListManager){
        _taskListManager = [[TaskListManager alloc]init];
        _taskListManager.delegate = self;
    }
    return _taskListManager;
}

-(NSMutableArray *)taskArr{
    if(!_taskArr){
        _taskArr = [NSMutableArray array];
    }
    return _taskArr;
}

-(GetUserInfoManager *)userInfoManager{
    if(!_userInfoManager){
        _userInfoManager = [[GetUserInfoManager alloc]init];
        _userInfoManager.delegate = self;
    }
    return _userInfoManager;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self getUserInfo];
    [self getTaskData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    
    [self.customNavigationBar setTitle:@"我的岛币"];
    CGFloat w300 = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w300 > self.currentAvailableHeight){
        w300 = self.currentAvailableHeight;
    }
    UIImageView *topBgImageView = [[UIImageView alloc]init];
    topBgImageView.image = [UIImage imageNamed:@"mine_point_bg"];
    topBgImageView.userInteractionEnabled = YES;
    [self.view addSubview:topBgImageView];
    [topBgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(w300);
    }];
    self.topBgImageView = topBgImageView;
   
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 68;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:NSClassFromString(@"MyCoinListCell") forCellReuseIdentifier:@"MyCoinListCell"];
    [self.view addSubview:self.tableView];
    
    CGFloat h = 140*(self.currentAvailableWidth-32)/375;
    CGFloat h100 = [DeviceUtils getAdaptedWidthForDesignWidth:100 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.topView = [[MyCoinTopView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,h100+h+54) andCurrentAvailableHeight:self.currentAvailableHeight];
    self.tableView.tableHeaderView = self.topView;
    self.topView.userModel = self.userModel;
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,76)];
    bottomView.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(16,0,self.currentAvailableWidth-32,16)];
    bgView.backgroundColor = [UIColor whiteColor];
    [bottomView addSubview:bgView];
    [bgView addRoundedCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
    self.tableView.tableFooterView = bottomView;
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat w300 = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(w300 > self.currentAvailableHeight){
                w300 = self.currentAvailableHeight;
            }
            [self.topBgImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(w300);
            }];
            self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat h = 140*(self.currentAvailableWidth-32)/375;
            CGFloat h100 = [DeviceUtils getAdaptedWidthForDesignWidth:100 andCurrentAvailableWidth:self.currentAvailableWidth];
            self.topView.frame = CGRectMake(0,0,self.currentAvailableWidth,h100+h+54);
            self.topView.currentAvailableWidth = self.currentAvailableWidth;
            self.topView.currentAvailableHeight = self.currentAvailableHeight;
            [self.topView refreshWidth];
            self.tableView.tableHeaderView = self.topView;
            self.topView.userModel = self.userModel;
            UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,76)];
            bottomView.backgroundColor = [UIColor clearColor];
            UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(16,0,self.currentAvailableWidth-32,16)];
            bgView.backgroundColor = [UIColor whiteColor];
            [bottomView addSubview:bgView];
            [bgView addRoundedCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
            self.tableView.tableFooterView = bottomView;
            
        });
    }
}

#pragma mark - 获取个人信息
-(void)getUserInfo{
    
    self.userInfoManager.userId = self.userModel.userId;
    [self.userInfoManager loadData];
    
}

#pragma mark - 获取任务列表
-(void)getTaskData{
    self.taskListManager.userId =  self.userModel.userId;
    [self.taskListManager loadData];
}

#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCoinListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCoinListCell"];
    if(indexPath.row < self.taskArr.count){
        TaskListModel *model = self.taskArr[indexPath.row];
        cell.model = model;
        __weak typeof(self)self_weak_ = self;
        [cell setToFinishBlock:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if(model.finished.integerValue == 0){
                    [(JPTabBarController *)self_weak_.tabBarController selectedtabVCWithIndex:0];
                    [self_weak_.navigationController popToRootViewControllerAnimated:NO];
                }
            });
        }];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.taskArr.count;
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.taskListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = dic[@"data"];
        NSArray *yearTaskArr = @[];
        for(NSInteger i = 0;i < arr.count;i++){
            NSDictionary *datadic = arr[i];
            if(datadic[@"mode"]){
                NSString *mode = [NSString stringWithFormat:@"%@",datadic[@"mode"]];
                NSArray *list = [TaskListModel mj_objectArrayWithKeyValuesArray:datadic[@"list"]];
                if(mode.integerValue == 2){
                    [self.taskArr addObjectsFromArray:list];
                }else if (mode.integerValue == 1){
                    yearTaskArr = list;
                }
            }
        }
        self.topView.userModel = self.userModel;
        self.topView.arr = yearTaskArr;
        [self.topView createYearTaskUI];
        [self.tableView reloadData];
    }
    
    
    if([manager isEqual:self.userInfoManager]){
        NSDictionary *dic = manager.response.content;
        self.userModel = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.userModel.goldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.goldNumber forKey:@"goldNumber"];
        }
        if(self.userModel.signCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.signCount forKey:@"signCount"];
        }
        if(self.userModel.addGoldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.addGoldNumber forKey:@"addGoldNumber"];
        }
        self.topView.userModel = self.userModel;
        if(self.topView.arr){
            [self.topView createYearTaskUI];
        }
    }
   
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}



@end
